package com.example.test1.support;


import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.format.Formatter;

import java.text.ParseException;
import java.util.Locale;

public class MoneyFormatter implements Formatter<Money> {
    @Override
    public Money parse(String text, Locale locale) throws ParseException {
        if (NumberUtil.isNumber(text)){
            return Money.of(CurrencyUnit.of("CNY"),NumberUtil.toBigDecimal(text));
        } else if (StrUtil.isNotEmpty(text)){
            String[] split = StrUtil.split(text, " ");
            if (split!=null && split.length==2
                    && StrUtil.equalsAnyIgnoreCase("CNY",split[0])
                    && NumberUtil.isNumber(split[1])){
                return Money.of(CurrencyUnit.of("CNY"),NumberUtil.toBigDecimal(split[1]));
            } else {
                throw new ParseException(text, 0);
            }
        }
        throw new ParseException(text, 0);
    }

    @Override
    public String print(Money money, Locale locale) {
        if (money == null){
            return null;
        }
        return money.getCurrencyUnit().getCode() + " " + money.getAmount();
    }
}
